'use strict';

const jwt = require('jsonwebtoken');
const { Controller } = require('egg');
const { Op } = require('sequelize');
const serviceName = 'admin';
class UserController extends Controller {
  //  用户列表
  async index() {
    const { query, service } = this.ctx;
    let { page, size, username, nickname } = query;
    page = Number(page) || 1;
    size = Number(size) || 10;

    const where = {};
    if (username) {
        where.username = { [Op.like]: `%${username}%` }
    }
    if (nickname) {
      where.nickname = { [Op.like]: `%${nickname}%` }
    }
    const users = await service[serviceName].getPage(where, page, size);
    this.ctx.success(users);
  }

  // 所有列表
  async allList() {
    const { query, service } = this.ctx;
    let { nickname } = query;
    let where = {};
    if (nickname) {
      where.nickname = { [Op.like]: `%${nickname}%` }
    }
    const user = await service[serviceName].allList(where);
    this.ctx.success(user);
  }

  // 删除用户
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[serviceName].deleteUserById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }

  // 查看
  async show() {
    const { params, service } = this.ctx;
    const findItem = await service[serviceName].findOne(params.id);
    this.ctx.success(findItem);
  }
  // 修改用户信息
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递用户ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[serviceName].updateUserById(id, infos);
    ctx.success(id, 200);
  }

  // 注册
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await ctx.service[serviceName].create(data);
    ctx.success(res);
  }

  // 登录
  async login() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    const user = await service[serviceName].login(data);
    user.token = jwt.sign(user, this.config.keys);
    ctx.success(user);
  }

  // 修改密码
  async updatePassword() {
    const { ctx } = this;
    const { request, service } = ctx;
    const data = request.body;
    await service[serviceName].updatePassword(data.id, data);
    ctx.success();
  }
}

module.exports = UserController;
